package com.rpcdemo.rpc.transport;

import com.rpcdemo.rpc.protocol.MyContent;
import com.rpcdemo.rpc.protocol.MyHeader;
import com.rpcdemo.util.PackMsg;
import com.rpcdemo.util.SeriaUtil;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;

import java.util.List;

public class ServerDecoder extends ByteToMessageDecoder {

    @Override
    protected void decode(ChannelHandlerContext ctx, ByteBuf buf, List<Object> out) throws Exception {

        while (buf.readableBytes() >= 103) {
            byte[] bytes = new byte[103];
            buf.getBytes(buf.readerIndex(), bytes);

            MyHeader reqHeader = (MyHeader) SeriaUtil.decode(bytes);

            if (buf.readableBytes() >= reqHeader.getDataLen() + 103) {
                buf.readBytes(103);

                byte[] bytes1 = new byte[(int) reqHeader.getDataLen()];
                buf.readBytes(bytes1);
                int flag = reqHeader.getFlag();
                if (flag == 0x14141414) {

                    MyContent reqBody = (MyContent) SeriaUtil.decode(bytes1);

                    PackMsg packMsg = new PackMsg();
                    packMsg.setContent(reqBody);
                    packMsg.setHeader(reqHeader);

                    out.add(packMsg);

                } else if (flag == 0x14141424) {

                    MyContent respBody = (MyContent) SeriaUtil.decode(bytes1);

                    PackMsg packMsg = new PackMsg();
                    packMsg.setContent(respBody);
                    packMsg.setHeader(reqHeader);

                    out.add(packMsg);

                }

            } else {

                break;
            }


        }

    }
}
